/**
 * 刷新循环修复工具
 * 专门用于检测和修复无限刷新问题
 */

// utils/refreshLoopFix.ts
const REFRESH_COUNT_KEY = 'refresh_count';
const REFRESH_TIMESTAMP_KEY = 'refresh_timestamp';
const MAX_REFRESH_COUNT = 5;
const TIME_WINDOW = 10000; // 10秒内

export const detectRefreshLoop = (): boolean => {
  try {
    const refreshCount = localStorage.getItem(REFRESH_COUNT_KEY);
    const lastRefreshTime = localStorage.getItem(REFRESH_TIMESTAMP_KEY);
    
    if (!refreshCount || !lastRefreshTime) {
      // 第一次访问，初始化计数器
      localStorage.setItem(REFRESH_COUNT_KEY, '1');
      localStorage.setItem(REFRESH_TIMESTAMP_KEY, Date.now().toString());
      return false;
    }
    
    const count = parseInt(refreshCount, 10);
    const timestamp = parseInt(lastRefreshTime, 10);
    const now = Date.now();
    
    // 检查是否在时间窗口内
    if (now - timestamp < TIME_WINDOW) {
      // 在时间窗口内，检查刷新次数
      if (count >= MAX_REFRESH_COUNT) {
        console.warn('检测到可能的刷新循环，已阻止进一步刷新');
        // 清除计数器
        localStorage.removeItem(REFRESH_COUNT_KEY);
        localStorage.removeItem(REFRESH_TIMESTAMP_KEY);
        return true;
      }
      
      // 增加计数
      localStorage.setItem(REFRESH_COUNT_KEY, (count + 1).toString());
    } else {
      // 超出时间窗口，重置计数器
      localStorage.setItem(REFRESH_COUNT_KEY, '1');
      localStorage.setItem(REFRESH_TIMESTAMP_KEY, now.toString());
    }
    
    return false;
  } catch (error) {
    console.error('检查刷新循环时出错:', error);
    return false;
  }
};

export const resetRefreshLoopDetection = (): void => {
  try {
    localStorage.removeItem(REFRESH_COUNT_KEY);
    localStorage.removeItem(REFRESH_TIMESTAMP_KEY);
  } catch (error) {
    console.error('重置刷新循环检测时出错:', error);
  }
};

// 页面加载完成后重置计数器
window.addEventListener('load', () => {
  setTimeout(() => {
    resetRefreshLoopDetection();
  }, 5000); // 5秒后重置，给应用足够时间初始化
});

export default {
  detectRefreshLoop,
  resetRefreshLoopDetection
};
